#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb
import redis
import json
import time
import sys
import threading

import smtp
import mysql

general_fmt = "moretv_p2p_group_general_%d"
group_attr_fmt = "moretv_p2p_group_attr_%s"
channelList = ["cctv5", "cntvcctv13", "cntvcctv1"]

reload(sys)
sys.setdefaultencoding("utf-8")

# struct of statisticDic :
# {
#     $groupId1: {
#         code : $channel,
#         peerSum : $peerSum,
#         time : $current_time
#     },
#     ...
# }
statisticDic = {}

rClient = redis.Redis(
    host = "10.10.218.112",
    port = 6379,
    db = 0
)

def getGeneralKeys() :
    keyList = mysql.queryRoute()
    #keyList = json.loads(keyList)
    return keyList

def parseRouteInfo(keyList, tableName) :
    curTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    count = 0
    for row in keyList :
        routeId = row[0]
        comment = row[1]
        # print routeId
        # print comment
        if not comment :
            continue
        routeInfo = rClient.hgetall(general_fmt % routeId)
        # struct of general_key :
        # {
        #     $groupId1: {
        #         code : $channel,
        #         peersStat : {
        #             1 : $num1,
        #             2 : $num2,
        #             3 : $num3,
        #             4 : $num4,
        #             5 : $num5
        #         }
        #     },
        #     $groupId2: {
        #         ...
        #     },
        #     ...
        # }
        for groupId in routeInfo :
            groupInfo = json.loads(routeInfo[groupId])
            code = groupInfo["code"]
            if code not in channelList :
                continue
            # print groupId
            count += 1
            peersStat = json.loads(groupInfo["peersStat"])
            peerSum = 0
            for depth in peersStat :
                peerSum += peersStat[depth]
            group_comment = comment + " " + code
            group_comment = group_comment.replace(" ", "_");
            # print group_comment
            mysql.insertData(tableName, group_comment, peerSum, curTime)
    print count
    print curTime


def do() :
    dayTime = time.strftime("%Y_%m_%d", time.localtime())
    tableName = "peers_%s" % dayTime
    keyList = getGeneralKeys()
    parseRouteInfo(keyList, tableName)

    #statisticDicStr = json.dumps(statisticDic, indent=4)
    #fp = open("stat", "wb")
    #fp.write(statisticDicStr)
    #fp.close()
    #print statisticDicStr
    #smtp.report(statisticDicStr)

def main() :
    while True :
        do()
        time.sleep(300)

if __name__ == "__main__" :
    main()
